/**
 * File: Intermediator.java
 * Created by: mhaimel
 * Created on: 7 Jul 2009
 * CVS:  $Id: Intermediator.java,v 1.1 2009/08/05 15:16:13 mhaimel Exp $
 */
package uk.ac.ebi.curtain.management.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import uk.ac.ebi.curtain.management.IInterceptor;
import uk.ac.ebi.curtain.management.InterceptorInfo;

/**
 * @author mhaimel
 *
 */
public class Intermediator implements IInterceptor<Serializable> {
	
	private Set<String> liveSet = new HashSet<String>();
	
	private List<IInterceptor<Serializable>> targetList = new ArrayList<IInterceptor<Serializable>>();

	public void registerSource(String name){
		this.liveSet.add(name);
	}
	
	@SuppressWarnings("unchecked")
	public void registerTarget(IInterceptor<? extends Serializable> contr){
		this.targetList.add((IInterceptor<Serializable>)contr);
	}
	
	public void handle(Serializable input, InterceptorInfo info) {
		for(IInterceptor<Serializable> inter : targetList){
			inter.handle(input, info);
		}
	}

	public synchronized void shutDown(boolean force, InterceptorInfo info) {
		liveSet.remove(info.getOriginName());
		if(force || liveSet.isEmpty()){
			for(IInterceptor<Serializable> inter : targetList){
				inter.shutDown(force,info);
			}
		}
	}	
}
